package net.oschina.app.ui;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import net.oschina.app.R;
import net.oschina.app.base.BaseActivity;
import net.oschina.app.bean.ShakeBean;
import net.oschina.app.protocol.ShakeProtocol;
import net.oschina.app.util.CommonUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/1/16.
 */

public class ShakeActivity extends BaseActivity {
    @BindView(R.id.iv_shake)
    ImageView    mIvShake;
    @BindView(R.id.iv_shake_icont)
    ImageView    mIvShakeIcont;
    @BindView(R.id.tv_shake_content1)
    TextView     mTvShakeContent1;
    @BindView(R.id.tv_shake_content2)
    TextView     mTvShakeContent2;
    @BindView(R.id.LL_shake)
    LinearLayout mLLShake;
    /**
     * 安卓晃动手机监听--“摇一摇”
     *
     * @author 单红宇
     */
//    public class TestSensorActivity extends Activity {

    private SensorManager sensorManager;
    private Vibrator      vibrator;

    private static final String TAG          = "ShakeActivity";
    private static final int    SENSOR_SHAKE = 10;
    private ImageView mIvYao;
    private ShakeBean mShakeBean;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shake);
        ButterKnife.bind(this);
        mIvYao = (ImageView) findViewById(R.id.iv_shake);//摇晃图片


        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (sensorManager != null) {// 注册监听器
            sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
            // 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (sensorManager != null) {// 取消监听器
            sensorManager.unregisterListener(sensorEventListener);
        }
    }

    /**
     * 重力感应监听
     */
    private SensorEventListener sensorEventListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            // 传感器信息改变时执行该方法
            float[] values = event.values;
            float x = values[0]; // x轴方向的重力加速度，向右为正
            float y = values[1]; // y轴方向的重力加速度，向前为正
            float z = values[2]; // z轴方向的重力加速度，向上为正
            Log.i(TAG, "x轴方向的重力加速度" + x + "；y轴方向的重力加速度" + y + "；z轴方向的重力加速度" + z);
            // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
            int medumValue = 19;// 三星 i9250怎么晃都不会超过20，没办法，只设置19了
            if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) {
                vibrator.vibrate(200);
                Message msg = new Message();
                msg.what = SENSOR_SHAKE;
                handler.sendMessage(msg);
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    /**
     * 动作执行
     */
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SENSOR_SHAKE:
                    Toast.makeText(ShakeActivity.this, "检测到摇晃，执行操作！", Toast.LENGTH_SHORT).show();
//                    Log.i(TAG, "检测到摇晃，执行操作！");
                    Alpha_Translate();
                    break;
            }
        }

    };

    //摇一摇之后的想应
    public void Alpha_Translate() {
        AnimationSet animationSet = new AnimationSet(true);
        AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
        alphaAnimation.setDuration(2000);
        animationSet.addAnimation(alphaAnimation);
        TranslateAnimation translateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f,  //X轴的开始位置
                Animation.RELATIVE_TO_SELF, 1.0f,  //X轴的结束位置
                Animation.RELATIVE_TO_SELF, 0f,  //Y轴的开始位置
                Animation.RELATIVE_TO_SELF, 1.0f);  //Y轴的结束位置
        translateAnimation.setDuration(2000);

        //摇摆
        TranslateAnimation alphaAnimation2 = new TranslateAnimation(150f, 350f, 50, 50);
        alphaAnimation2.setDuration(1000);
        alphaAnimation2.setRepeatCount(Animation.INFINITE);
        alphaAnimation2.setRepeatMode(Animation.REVERSE);



        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {//动画结束
                //TODO:设置数据
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ShakeProtocol shakeProtocol = new ShakeProtocol() ;
                        mShakeBean = shakeProtocol.getData(0);
                        CommonUtils.runOnMainThread(new Runnable() {
                            @Override
                            public void run() {
                                mLLShake.setVisibility(View.VISIBLE);
                                Glide.with(getApplicationContext()).load(mShakeBean.getImage()).into(mIvShakeIcont);
                                mTvShakeContent1.setText(mShakeBean.getTitle());
                                mTvShakeContent2.setText(mShakeBean.getDetail());

                            }
                        });

                    }
                }).start();


            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        animationSet.addAnimation(translateAnimation);
        animationSet.addAnimation(alphaAnimation2);
        mIvYao.startAnimation(animationSet);
    }

}

